package com.cn.wanxi.servlet.manage.user;

import com.cn.wanxi.dto.UserModelDto;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        1.拿到页面的值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String sessionCode = req.getSession().getAttribute("code").toString();
//        判断页面拿来的code是否和我们传递到页面的图片里面的code是否一致，如果是，则通过验证，如果不是，则返回，验证码错误
//      2封装
        UserModelDto userModelDto = new UserModelDto();
        userModelDto.setUsername(username);
        userModelDto.setPassword(password);
        userModelDto.setCode(code);
        userModelDto.setSessionCode(sessionCode);
//        3.逻辑层
        IUserService iUserService = new UserServiceImpl();
        ResultModel resultModel = iUserService.loginResult(userModelDto);

        //只有登录成功才能将用户名放入session
        if (resultModel.getCode().equals("200")) {
            req.getSession().setAttribute("username", username);
        }
//        4.返回数据
        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        resp.getWriter().println(jsonArray);
    }
}
